package linear_list.leetcode.medium;

/**
 * @author bruin_du
 * @description 两数相加
 * @date 2022/6/5 21:30
 **/
public class Num2_AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while(l1 != null || l2 != null){
            int sum = carry;
            if(l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            carry = sum / 10;
            sum %= 10;
            ListNode node = new ListNode(sum);
            cur = cur.next = node;
        }
        if(carry != 0){
            ListNode node = new ListNode(carry);
            cur.next = node;
        }
        return head.next;
    }
}
